package io;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class demo8 {
    private static void readFile(){
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("./test.txt");
            while (true) {
                byte[] bytes = new byte[1024];
                int len = inputStream.read(bytes);
                if (len == -1) {
                    break;
                }
                for (int i = 0; i < len; i++) {
                    System.out.printf("%x ",bytes[i]);
                }
                System.out.println();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally{
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private static void readFile1(){
        //try with resource 语法来简化上述代码
        //try执行后，就会自动调用close
        try(InputStream inputStream = new FileInputStream("./test.txt")){
            while (true) {
                byte[] bytes = new byte[1024];
                int len = inputStream.read(bytes);
                if (len == -1) {
                    break;
                }
                for (int i = 0; i < len; i++) {
                    System.out.printf("%x ",bytes[i]);
                }
                System.out.println();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } 
    }

    public static void main(String[] args){
        readFile();
    }
}
